﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace MvcShop.Extensions.Caching
{
    internal class RecordWriter : TextWriter
    {
        public RecordWriter(TextWriter innerWriter)
        {
            this.m_innerWriter = innerWriter;
        }

        private TextWriter m_innerWriter;
        private List<StringBuilder> m_recorders = new List<StringBuilder>();

        public override Encoding Encoding
        {
            get { return this.m_innerWriter.Encoding; }
        }

        public override void Write(char value)
        {
            this.m_innerWriter.Write(value);

            if (this.m_recorders.Count > 0)
            {
                foreach (var recorder in this.m_recorders)
                {
                    recorder.Append(value);
                }
            }
        }

        public override void Write(string value)
        {
            if (value != null)
            {
                this.m_innerWriter.Write(value);

                if (this.m_recorders.Count > 0)
                {
                    foreach (var recorder in this.m_recorders)
                    {
                        recorder.Append(value);
                    }
                }
            }
        }

        public override void Write(char[] buffer, int index, int count)
        {
            this.m_innerWriter.Write(buffer, index, count);

            if (this.m_recorders.Count > 0)
            {
                foreach (var recorder in this.m_recorders)
                {
                    recorder.Append(buffer, index, count);
                }
            }
        }

        public void AddRecorder(StringBuilder recorder)
        {
            this.m_recorders.Add(recorder);
        }

        public void RemoveRecorder(StringBuilder recorder)
        {
            this.m_recorders.Remove(recorder);
        }
    }
}
